#include "FatFs.hpp"
#include "ff.h"
#include <stdio.h>
#include <string.h>
#include "usart1_printf.h"

// 不再使用 new，不再使用 fatfs_instances 全局指针数组
FatFs* FatFs::getInstance(unsigned char drive_number) {
    // 最多支持 10 个卷：0 ~ 9
    static FatFs instances[10] = {
        FatFs(0), FatFs(1), FatFs(2), FatFs(3), FatFs(4),
        FatFs(5), FatFs(6), FatFs(7), FatFs(8), FatFs(9)
    };

    if (drive_number >= 10) {
        return nullptr;  // 越界保护
    }

    FatFs* inst = &instances[drive_number];
    static bool initialized[10] = { false };
    if (!initialized[drive_number]) {
        initialized[drive_number] = inst->init();  // 只初始化一次
    }

    return inst;
}

FatFs::FatFs(unsigned char drive_number)
    : drive_number(drive_number) {}

bool FatFs::init() {
    char path[4];
    sprintf(path, "%d:", drive_number);
    FRESULT res = f_mount(&fs, path, 1);  // 第三个参数1表示立即挂载
    return (res == FR_OK);
}

bool FatFs::open(const char* path, BYTE mode) {
    return (f_open(&file, path, mode) == FR_OK);
}

int FatFs::read(void* buffer, UINT size) {
    UINT br;
    return (f_read(&file, buffer, size, &br) == FR_OK) ? br : -1;
}

int FatFs::write(const void* buffer, UINT size) {
    UINT bw;
    return (f_write(&file, buffer, size, &bw) == FR_OK) ? bw : -1;
}

void FatFs::close() {
    f_close(&file);
}
